﻿//108. 将有序数组转换为二叉搜索树
//给你一个整数数组 nums ，其中元素已经按 升序 排列，请你将其转换为一棵平衡二叉搜索树。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void bulid(vector<int>& nums, TreeNode*& root, int begin, int end)
    {
        if (begin > end)
        {
            root = nullptr;
            return;
        }
        int mid = (begin + end) / 2;
        root = new TreeNode;
        root->val = nums[mid];
        root->right = nullptr;
        root->left = nullptr;
        bulid(nums, root->left, begin, mid - 1);
        bulid(nums, root->right, mid + 1, end);
    }
    TreeNode* sortedArrayToBST(vector<int>& nums)
    {
        TreeNode* root = nullptr;
        bulid(nums, root, 0, nums.size() - 1);
        return root;
    }
};